import { getUserInfo, login, logout } from "@/api/auth";
import { defineStore } from "pinia";
import type { UserState } from "./typing";
import type { LoginParams } from "@/api/auth/typing";
import { ACCESS_TOKEN, REFRESH_TOKEN } from "@/utils/storage/key";
import { useMenuStore } from "../menu";
import { queryUserRoleList } from "@/api/system/role";
import { queryOrganizationList } from "@/api/system/organization";
import router from "@/router";
import { clearLoginInfo } from "@/utils/storage";

const initState = (): UserState => ({
  userInfo: {
    avatar: null,
    avatarUrl: null,
    userId: null,
    username: null,
    password: null,
    defaultRoleId: null,
    defaultOrganizationId: null,
    nickname: "用户",
    integration: 0,
    fnApiMap: {},
  },
  roleList: [],
  orgList: [],
});

export const useUserStore = defineStore("user", {
  state: () => initState(),
  getters: {
    currentRole: (state) => {
      return state.roleList.find(
        (f) => f.roleId == state.userInfo.defaultRoleId
      );
    },
    currentOrg: (state) => {
      return state.orgList.find(
        (f) => f.organizationId == state.userInfo.defaultOrganizationId
      );
    },
  },
  actions: {
    /**登录 */
    async login(params: LoginParams) {
      const response = await login(params);
      const { success, result } = response;
      if (success) {
        localStorage.setItem(ACCESS_TOKEN, result.accessToken);
        localStorage.setItem(REFRESH_TOKEN, result.refreshToken);
        // 获取用户信息
        await this.getUserInfo();
        // 查询用户角色信息-异步
        this.getRoleList();
        // 查询用户组织信息-异步
        this.getOrgList();
        // 获取菜单树
        const menuStore = useMenuStore();
        await menuStore.getMenuTree();
      }
      return response;
    },
    /**获取用户信息 */
    async getUserInfo() {
      const response = await getUserInfo();
      const { success, result } = response;
      if (success) {
        this.userInfo = result;
      }
      return response;
    },
    /**获取当前用户的角色列表 */
    async getRoleList() {
      const response = await queryUserRoleList();
      const { success, result } = response;
      if (success) {
        this.roleList = result;
      }
      return response;
    },
    /**获取当前用户的组织列表 */
    async getOrgList() {
      const response = await queryOrganizationList();
      const { success, result } = response;
      if (success) {
        this.orgList = result;
      }
      return response;
    },
    /**退出登录 */
    async logout() {
      const response = await logout();
      if (response.success) {
        // 重定向导登录页
        const [path] = router.currentRoute.value.fullPath.split("?");
        router.replace({ path: "/white-path/login", query: { path } });
        // 除了主题配置，其他清空
        clearLoginInfo();
        this.$state = initState();
        const menuStore = useMenuStore();
        menuStore.$reset();
      }
      return response;
    },
  },
});
